//随笔脚本
const { prompt } = require('enquirer')
const { writeFile } = require('fs')
const data = require('../essays/index.json')

const padZero = num => (num < 10 ? `0${num}` : num)
const formatDate = date => {
  const [year, month, day] = date.split('-')
  return `${year}-${padZero(month)}-${padZero(day)}`
}

async function writeEssayContent() {
  const { content } = await prompt({
    type: 'input',
    name: 'content',
    message: 'Input Essay',
  })
  return content
}

async function main() {
  const content = await writeEssayContent()
  data.essays.push({
    date: formatDate(new Date().toLocaleDateString().replaceAll('/', '-')),
    content,
  })
  await writeFile('essays/index.json', JSON.stringify(data, null, 2), err => {
    if (err) {
      console.log('An error has occurred ', err)
      return
    }
    console.log('written successfully')
  })
}

main()
